package org.dev.biz_search.views

import android.content.Context
import android.util.AttributeSet
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import kotlinx.android.synthetic.main.layout_quick_search_list_item.*
import org.dev.biz_search.KeyWord
import org.dev.biz_search.R
import org.dev.hi.hiui.item.HiAdapter
import org.dev.hi.hiui.item.HiDataItem
import org.dev.hi.hiui.item.HiViewHolder

/**
 * Author WenPing
 * CreateTime 2021/8/31.
 * Description:快搜联想词列表
 */
class QuickSearchView @JvmOverloads constructor(
    context: Context,
    attributeSet: AttributeSet? = null,
    defStyle: Int = 0
) : RecyclerView(context, attributeSet, defStyle) {

    init {
        layoutManager = LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false)
        adapter = HiAdapter(context)
        layoutParams = LayoutParams(
            LayoutParams.MATCH_PARENT,
            LayoutParams.MATCH_PARENT
        )
    }

    fun bindData(keyWords: List<KeyWord>, callback: (KeyWord) -> Unit) {
        val dataItems = mutableListOf<QuickSearchItem>()
        for (keyword in keyWords) {
            dataItems.add(QuickSearchItem(keyword, callback))
        }
        val hiAdapter = adapter as HiAdapter
        hiAdapter.clearItems()
        hiAdapter.addItems(dataItems, true)
    }

    /**
     * 创建viewHolder
     */
    private inner class QuickSearchItem(val keyWord: KeyWord, val callback: (KeyWord) -> Unit) :
        HiDataItem<KeyWord, HiViewHolder>() {
        override fun onBindData(vh: HiViewHolder, position: Int) {
            vh.item_title.text = keyWord.keyWord
            vh.itemView.setOnClickListener {
                callback(keyWord)
            }
        }

        override fun getItemLayoutRes(): Int = R.layout.layout_quick_search_list_item

    }


}